package com.foodplus.www.presenter;

import android.content.SharedPreferences;

import com.foodplus.www.api.BaseSubscriber;
import com.foodplus.www.api.ExceptionHandle;
import com.foodplus.www.bean.login.CodeBean;
import com.foodplus.www.bean.login.LoginBean;
import com.foodplus.www.foodplus.MyApp;
import com.foodplus.www.model.impl.LoginModelImpl;
import com.foodplus.www.view.impl.LoginView;

import java.util.Map;

/**
 * Created by WangZhiChao on 2016/11/1.
 */

public class LoginPresenter {
    LoginView loginView;

    public LoginPresenter(LoginView loginView) {
        this.loginView = loginView;
    }

    public void SendCode(Map<String, String> params) {
        new LoginModelImpl().getLoginCode(new BaseSubscriber<CodeBean>() {


            @Override
            public void onSuccess(CodeBean codeBean) {
                loginView.onCodeSend(codeBean);
            }

            @Override
            public void onFail(ExceptionHandle.ResponeThrowable e) {
                loginView.onFail(e);
            }

            @Override
            public void onFinished() {
                loginView.onFinish();
            }
        }, params);
    }

    public void Login(Map<String, String> params) {
        new LoginModelImpl().GetLoginResult(new BaseSubscriber<LoginBean>() {
            @Override
            public void onSuccess(LoginBean loginBean) {
                loginView.onLoginResult(loginBean);
            }

            @Override
            public void onFail(ExceptionHandle.ResponeThrowable e) {
                loginView.onFail(new ExceptionHandle.ResponeThrowable(new Throwable("登录失败"), 10008));
            }

            @Override
            public void onFinished() {
                loginView.onFinish();
            }
        }, params);
    }


    public static void saveUserState(LoginBean loginBean) {
        SharedPreferences.Editor edit = MyApp.getInstance().getUserPreferences().edit();
        LoginBean.DatasBean data = loginBean.getDatas();
        edit.putString("username", data.getUsername());
        edit.putString("userid", data.getUserid());
        edit.putString("key", data.getKey());
        edit.putString("userImg", data.getUserImg());
        edit.putString("userGender", data.getUserGender());
        edit.putString("member_mobile", data.getMember_mobile());
        edit.putString("member_nick", data.getMember_nick());
        edit.putString("member_avatar", data.getMember_avatar());
        edit.apply();
        MyApp.getInstance().setLoggedIn(true);
    }
}
